import { useState, useEffect } from 'react';
import styles from './index.module.css';
import Nabar from '../../conpoment/Nabar';
import SelectedItemsModal, { SelectedItem } from '../../conpoment/SelectedItemsModal';
import image from './img/image.png';
import { useNavigate } from 'react-router-dom';


function Index() {
    const nav=useNavigate()
    const [activeTab, setActiveTab] = useState('药品');
    const [selectedCategory, setSelectedCategory] = useState(0);
    const [cart, setCart] = useState<{ [key: number]: number }>({}); // 购物车 {商品ID: 数量}
    const [showCartModal, setShowCartModal] = useState(false); // 购物车弹框状态
    const [selectedItems, setSelectedItems] = useState<SelectedItem[]>([]); // 已选项目列表
    // 模拟数据 - 按标签页分类
    const tabData = {
        '药品': [
            {
                id: 1,
                name: '新冠预防中药',
                products: [
                    {
                        id: 1,
                        name: '新冠预防中药 (正常人群) 1剂',
                        description: '功效:主要提高免疫力,预防新冠疾病',
                        price: 11.80,
                        image: image,
                        tags: ['处方药', '限购5剂'],
                        maxQuantity: 5,
                        isPrescription: true,
                        unit: '剂'
                    },
                    {
                        id: 2,
                        name: '新冠预防中药 (体弱人群) 1剂',
                        description: '功效:主要提高免疫力,预防新冠疾病',
                        price: 11.80,
                        image: image,
                        tags: ['处方药', '限购5剂'],
                        maxQuantity: 5,
                        isPrescription: true,
                        unit: '剂'
                    },
                    {
                        id: 3,
                        name: '新冠预防中药 (儿童人群) 1剂',
                        description: '功效:主要提高免疫力,预防新冠疾病',
                        price: 9.80,
                        image: image,
                        tags: ['处方药'],
                        isPrescription: true,
                        unit: '剂'
                    }
                ]
            },
            {
                id: 2,
                name: '普通用药',
                products: [
                    {
                        id: 4,
                        name: '感冒清热颗粒',
                        description: '功效:清热解毒,疏风散寒',
                        price: 15.50,
                        image:image,
                        tags: ['非处方药'],
                        isPrescription: false,
                        unit: '盒'
                    }
                ]
            },
            {
                id: 3,
                name: '感冒用药 (非处方)',
                products: [
                    {
                        id: 5,
                        name: '板蓝根颗粒',
                        description: '功效:清热解毒,凉血利咽',
                        price: 8.90,
                        image:image,
                        tags: ['非处方药'],
                        isPrescription: false,
                        unit: '盒'
                    }
                ]
            }
        ],
        '检查': [
            {
                id: 1,
                name: '影像检查',
                products: [
                    {
                        id: 6,
                        name: '胸部CT检查',
                        description: '胸部CT平扫检查',
                        price: 280.00,
                        image: image,
                        tags: ['影像检查'],
                        maxQuantity: 1,
                        isPrescription: true,
                        unit: '次'
                    },
                    {
                        id: 7,
                        name: '腹部B超检查',
                        description: '腹部B超常规检查',
                        price: 120.00,
                        image: image,
                        tags: ['影像检查'],
                        maxQuantity: 1,
                        isPrescription: true,
                        unit: '次'
                    }
                ]
            },
            {
                id: 2,
                name: '心电图检查',
                products: [
                    {
                        id: 8,
                        name: '动态心电图',
                        description: '24小时动态心电图检查',
                        price: 150.00,
                        image: image,
                        tags: ['心电图'],
                        maxQuantity: 1,
                        isPrescription: true,
                        unit: '次'
                    }
                ]
            }
        ],
        '检验': [
            {
                id: 1,
                name: '血液检查',
                products: [
                    {
                        id: 9,
                        name: '血常规',
                        description: '全血细胞计数分析',
                        price: 15.00,
                        image: image,
                        tags: ['血液检查'],
                        maxQuantity: 1,
                        isPrescription: true,
                        unit: '次'
                    },
                    {
                        id: 10,
                        name: '生化全套',
                        description: '肝功能、肾功能等生化指标',
                        price: 85.00,
                        image: image,
                        tags: ['血液检查'],
                        maxQuantity: 1,
                        isPrescription: true,
                        unit: '次'
                    }
                ]
            },
            {
                id: 2,
                name: '尿液检查',
                products: [
                    {
                        id: 11,
                        name: '尿常规检查',
                        description: '尿液常规分析',
                        price: 12.00,
                        image: image,
                        tags: ['尿液检查'],
                        maxQuantity: 1,
                        isPrescription: true,
                        unit: '次'
                    }
                ]
            }
        ]
    };
    // 获取当前标签页的分类数据
    const categories = tabData[activeTab as keyof typeof tabData] || [];
    // 获取当前分类的商品
    const currentProducts = categories[selectedCategory]?.products || [];

    // 初始化已选项目列表
    useEffect(() => {
        updateSelectedItems();
    }, [cart]);
    // 标签页切换时重置选中分类
    const handleTabChange = (tab: string) => {
        setActiveTab(tab);
        setSelectedCategory(0); // 重置为第一个分类
    };
    // 更新商品数量
    const updateQuantity = (productId: number, quantity: number) => {
        const product = currentProducts.find(p => p.id === productId);
        const maxQty = product?.maxQuantity || 999;

        if (quantity <= 0) {
            const newCart = { ...cart };
            delete newCart[productId];
            setCart(newCart);
            // 同时更新已选项目列表
            updateSelectedItems();
        } else if (quantity <= maxQty) {
            setCart(prev => ({
                ...prev,
                [productId]: quantity
            }));
            // 同时更新已选项目列表
            updateSelectedItems();
        }
    };

    // 更新已选项目列表
    const updateSelectedItems = () => {
        const items: SelectedItem[] = [];
        Object.entries(cart).forEach(([productId, quantity]) => {
            if (quantity > 0) {
                // 在所有标签页的数据中查找商品
                for (const tabKey in tabData) {
                    const tabCategories = tabData[tabKey as keyof typeof tabData];
                    const product = tabCategories.flatMap(c => c.products).find(p => p.id === parseInt(productId));
                    if (product) {
                        items.push({
                            id: product.id,
                            name: product.name,
                            price: product.price,
                            quantity: quantity,
                            type: tabKey === '药品' ? 'medicine' : tabKey === '检查' ? 'check' : 'test',
                            tags: product.tags,
                            unit: product.unit,
                            isPrescription: product.isPrescription
                        });
                        break;
                    }
                }
            }
        });
        setSelectedItems(items);
    };

    // 处理已选项目数量更新
    const handleUpdateQuantity = (id: number, quantity: number) => {
        if (quantity <= 0) {
            const newCart = { ...cart };
            delete newCart[id];
            setCart(newCart);
        } else {
            setCart(prev => ({
                ...prev,
                [id]: quantity
            }));
        }
        updateSelectedItems();
    };

    // 处理移除项目
    const handleRemoveItem = (id: number) => {
        const newCart = { ...cart };
        delete newCart[id];
        setCart(newCart);
        updateSelectedItems();
    };

    // 处理清空所有项目
    const handleClearAll = () => {
        setCart({});
        setSelectedItems([]);
    };
    // 获取商品数量
    const getQuantity = (productId: number) => {
        return cart[productId] || 0;
    };
    // 计算总价 - 计算所有标签页的总和
    const calculateTotal = () => {
        return Object.entries(cart).reduce((total, [productId, quantity]) => {
            // 在所有标签页的数据中查找商品
            let product = null;
            for (const tabKey in tabData) {
                const tabCategories = tabData[tabKey as keyof typeof tabData];
                product = tabCategories.flatMap(c => c.products).find(p => p.id === parseInt(productId));
                if (product) break;
            }
            return total + (product ? product.price * quantity : 0);
        }, 0);
    };
    // 获取已选商品数量
    const getSelectedCount = () => {
        return Object.values(cart).reduce((sum, quantity) => sum + quantity, 0);
    };

    return (
        <div className={styles.container}>
            {/* 头部导航 */}
            <Nabar title='开单申请' sticky={false} />
            {/* 开单记录链接 */}
            {/* 标签页 */}
            <div className={styles.headerRight}>
                <div className={styles.tabs}>
                    <div
                        className={`${styles.tab} ${activeTab === '药品' ? styles.activeTab : ''}`}
                        onClick={() => handleTabChange('药品')}
                    >
                        药品
                    </div>
                    <div
                        className={`${styles.tab} ${activeTab === '检查' ? styles.activeTab : ''}`}
                        onClick={() => handleTabChange('检查')}
                    >
                        检查
                    </div>
                    <div
                        className={`${styles.tab} ${activeTab === '检验' ? styles.activeTab : ''}`}
                        onClick={() => handleTabChange('检验')}
                    >
                        检验
                    </div>
                </div>
                <div className={styles.recordLink}>
                    <span onClick={() => console.log('查看开单记录')}>开单记录 &gt;</span>
                </div>

            </div>



            <div className={styles.content}>
                {/* 左侧分类列表 */}
                <div className={styles.sidebar}>
                    {categories.map((category, index) => (
                        <div
                            key={category.id}
                            className={`${styles.categoryItem} ${selectedCategory === index ? styles.selectedCategory : ''}`}
                            onClick={() => setSelectedCategory(index)}
                        >
                            {category.name}
                        </div>
                    ))}
                </div>

                {/* 右侧商品列表 */}
                <div className={styles.productList}>
                    {currentProducts.map((product) => (
                        <div key={product.id} className={styles.productItem}>
                            <div className={styles.productImage}>
                                <img src={product.image} alt={product.name} />
                            </div>
                            <div className={styles.productInfo}>
                                <div className={styles.productName}>{product.name}</div>
                                <div className={styles.productDescription}>{product.description}</div>
                                <div className={styles.productPrice}>
                                    ¥{product.price.toFixed(2)}
                                    <div className={styles.quantitySelector}>
                                        <button
                                            className={styles.quantityBtn}
                                            onClick={() => updateQuantity(product.id, getQuantity(product.id) - 1)}
                                            disabled={getQuantity(product.id) <= 0}
                                        >
                                            -
                                        </button>
                                        <input
                                            type="number"
                                            value={getQuantity(product.id)}
                                            onChange={(e) => updateQuantity(product.id, parseInt(e.target.value) || 0)}
                                            className={styles.quantityInput}
                                            min="0"
                                            max={product.maxQuantity || 999}
                                        />
                                        <button
                                            className={styles.quantityBtn}
                                            onClick={() => updateQuantity(product.id, getQuantity(product.id) + 1)}
                                            disabled={getQuantity(product.id) >= (product.maxQuantity || 999)}
                                        >
                                            +
                                        </button>
                                    </div>
                                </div>
                                <div className={styles.productTags}>
                                    {product.tags.map((tag, index) => (
                                        <span
                                            key={index}
                                            className={`${styles.tag} ${tag.includes('处方') ? styles.prescriptionTag : styles.limitTag}`}
                                        >
                                            {tag}
                                        </span>
                                    ))}
                                </div>
                            </div>

                        </div>
                    ))}
                </div>
            </div>

            {/* 底部购物车 */}
            <div className={styles.footer}>
                <div 
                    className={styles.cartInfo}
                    onClick={() => setShowCartModal(true)}
                    style={{ cursor: 'pointer' }}
                >
                    <div className={styles.cartIcon}>
                        <span>📋</span>
                    </div>
                    <div className={styles.cartText}>
                        <div>已选 {getSelectedCount()} 项</div>
                        <div className={styles.totalPrice}>合计: ¥ {calculateTotal().toFixed(2)}</div>
                    </div>
                </div>
                <button
                    className={styles.submitBtn}
                    onClick={() => {
                        // 收集所有商品数据
                        const allProducts: any[] = [];
                        for (const tabKey in tabData) {
                            const tabCategories = tabData[tabKey as keyof typeof tabData];
                            tabCategories.forEach(category => {
                                allProducts.push(...category.products);
                            });
                        }
                        
                        // 跳转到开单确认页面，传递购物车数据
                        nav('/self_order', {
                            state: {
                                cart: cart,
                                products: allProducts
                            }
                        });
                    }}
                    disabled={getSelectedCount() === 0}
                >
                    提交
                </button>
            </div>

            {/* 已选项目弹窗 */}
            <SelectedItemsModal
                isOpen={showCartModal}
                onClose={() => setShowCartModal(false)}
                items={selectedItems}
                onUpdateQuantity={handleUpdateQuantity}
                onRemoveItem={handleRemoveItem}
                onClearAll={handleClearAll}
                onSubmit={() => {
                    // 收集所有商品数据
                    const allProducts: any[] = [];
                    for (const tabKey in tabData) {
                        const tabCategories = tabData[tabKey as keyof typeof tabData];
                        tabCategories.forEach(category => {
                            allProducts.push(...category.products);
                        });
                    }
                    
                    // 跳转到开单确认页面，传递购物车数据
                    nav('/self_order', {
                        state: {
                            cart: cart,
                            products: allProducts
                        }
                    });
                }}
            />
        </div>
    );
}

export default Index;
